package com.whq.knowverywell.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.whq.knowverywell.R;
import com.whq.knowverywell.activity.ContentFragment.OnSumDataListener;
import com.whq.knowverywell.activity.barcode.BarcodeActivity;
import com.whq.knowverywell.activity.barcode.BarcodeActivity.Scan;
import com.whq.knowverywell.adapter.ProductSearchAdapter;
import com.whq.knowverywell.business.http.model.ProductSalesReturn;
import com.whq.knowverywell.business.model.ProductSalesRecord;
import com.whq.knowverywell.task.GoodsTask;
import com.whq.knowverywell.util.DisplayUtil;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.TipUtil;
import com.whq.knowverywell.util.constant.ModelConstant;
import com.whq.knowverywell.util.constant.ParamConstant;

/**
 * product search (because the component of the page is different from the
 * others, it is not suitable for fragment)
 * 
 * @author daiwei
 * 
 */
public class ProductSearchActivity extends BaseLoginActivity implements GoodsTask.ResultDataListener,
        ActionBar.OnNavigationListener, OnSumDataListener {
    private static final String TAG = ProductSearchActivity.class.getSimpleName();

    private ListView mListView;
    private EditText mSearchEditext;
    private ImageView mSearchImageView, mScanImageView;
    private LinearLayout mBottomLinearLayout;
    private ProductSearchAdapter mAdapter;
    private GoodsTask mGoodsTask;

    private boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.d(TAG, "onCreate start ...");
        setTheme(R.style.Theme_Sherlock_Light);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_search);

        mSumTextView = (TextView) findViewById(R.id.sum_textview);
        mAmountTextView = (TextView) findViewById(R.id.amount_textview);
        mSearchImageView = (ImageView) findViewById(R.id.search_imageview);
        mSearchImageView.setOnClickListener(this);
        mScanImageView = (ImageView) findViewById(R.id.scan_imageview);
        mScanImageView.setOnClickListener(this);
        // TODO add suggestion
        mSearchEditext = (EditText) findViewById(R.id.search_editext);
        mSearchEditext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        mSearchEditext.setOnEditorActionListener(new OnEditorActionListener() {
            
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                doSearch();
                return true;
            }
        });
        mListView = (ListView) findViewById(R.id.search_result_listview);
        mListView.setCacheColorHint(-000);
        // mListView.setSelector(-000);
        mAdapter = new ProductSearchAdapter(this, new ArrayList<ProductSalesRecord>());
        mListView.setAdapter(mAdapter);
        mHiddenManagerImageView = (ImageView) findViewById(R.id.manager_imageview);
        mBottomLinearLayout = (LinearLayout) findViewById(R.id.bottom_linearlayout);

        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.top_menu_bg));
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.homeitems,
                R.layout.self_sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.self_sherlock_spinner_dropdown_item);

        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, (OnNavigationListener) this);
        getSupportActionBar().setSelectedNavigationItem(ModelConstant.BUSINESS_TYPE_GOODS - 1);
    }

    @Override
    public void onClick(View v) {
        LogUtil.d(TAG, "onClick view id[" + v.getId() + "}");
        super.onClick(v);

        switch (v.getId()) {
        case R.id.search_imageview:
            doSearch();
            break;

        case R.id.scan_imageview:
            doScan();
            break;

        default:
            break;
        }
    }

    @Override
    protected void getParameters() {
        super.getParameters();
        Intent intent = getIntent();
        if (intent != null) {
            itemId = intent.getIntExtra(ParamConstant.BUNDLE_KEY_ITEM_ID, -1);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        SubMenu sub = menu.addSubMenu("管理");
        sub.setIcon(R.drawable.btn_set);
        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mManagerPopupWindow != null && !mManagerPopupWindow.isShowing()) {
            mManagerPopupWindow.showAsDropDown(mHiddenManagerImageView, 0, DisplayUtil.px2dip(-60, mDisplayMetrics.density));
        }
        return true;
    }

    @Override
    public void onSumData(int durationType, long totalSalesVolume, double totalSalesAmount) {

    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        if (!isFirst) {
            Intent intent = new Intent();
            intent.setClass(this, ContentFrameActivity.class);
            intent.putExtra(ParamConstant.BUNDLE_KEY_ITEM_ID, itemPosition + 1);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            this.finish();
        } else {
            isFirst = false;
        }
        return true;
    }

    @Override
    public String getProductNo() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void showSortPopupWindow(View anchor) {
        // TODO Auto-generated method stub

    }

    @Override
    public void showManagerPopupWindow(View anchor) {
        // TODO Auto-generated method stub

    }

    @Override
    public void handleData(ProductSalesReturn goodsResult) {
        LogUtil.d(TAG, "handleData start ...");
        closeProgressDialog();

        if (goodsResult == null) {
            TipUtil.tipDescription(this, "没有符合条件的数据.");
            mListView.setVisibility(View.INVISIBLE);
            mBottomLinearLayout.setVisibility(View.INVISIBLE);
            return;
        }

        List<ProductSalesRecord> records = goodsResult.getRecordList();
        if (records == null || records.size() == 0) {
            TipUtil.tipDescription(this, "没有符合条件的数据.");
            mListView.setVisibility(View.INVISIBLE);
            mBottomLinearLayout.setVisibility(View.INVISIBLE);
            return;
        }

        // show detail table
        int len = records.size();
        List<ProductSalesRecord> resultList = new ArrayList<ProductSalesRecord>();
        List<ProductSalesRecord> tmpList = new ArrayList<ProductSalesRecord>();
        for (int i = 0; i < len; i++) {
            ProductSalesRecord record = records.get(i);
            LogUtil.d(
                    TAG,
                    " code[" + record.getCode() + "]" + " fullpayment[" + record.getFullPayment() + "]" + " imgurl["
                            + record.getImageUrl() + "]" + " name[" + record.getName() + "]" + " salesamount["
                            + record.getSalesAmount() + "]" + " code[" + record.getCode() + "]" + " salesvolume["
                            + record.getSalesVolume() + "]" + " stockqty[" + record.getStockQty() + "]");
            String productBarCode = record.getCode();
            if (productNo.equals(productBarCode)) {
                resultList.add(record);
            } else {
                tmpList.add(record);
            }
        }
        resultList.addAll(tmpList);
        mAdapter = new ProductSearchAdapter(this, resultList);
        mListView.setAdapter(mAdapter);
        mListView.setVisibility(View.VISIBLE);
        
        // show total
//        String salesAmount = goodsResult.getTotalSalesAmount() + "";
        String salesCount = goodsResult.getTotalSalesVolume() + "";
        TextView totalSalesCountTextView = (TextView) mBottomLinearLayout.findViewById(R.id.sum_textview);
        totalSalesCountTextView.setText(salesCount);
        TextView totalSalesAmountTextView = (TextView) mBottomLinearLayout.findViewById(R.id.amount_textview);
        totalSalesAmountTextView.setText(new DecimalFormat(",###").format(goodsResult.getTotalSalesAmount()));
        mBottomLinearLayout.setVisibility(View.VISIBLE);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.d(TAG, "onActivityResult start ...");
        LogUtil.d(TAG, "requestCode[" + requestCode + "] resultCode[" + resultCode + "]");
        super.onActivityResult(requestCode, resultCode, data);
        
        switch (resultCode) {
        case RESULT_OK:
            String result = data.getStringExtra(Scan.RESULT);
            mSearchEditext.setText(result);
            doSearch();
            break;
        default:
            break;
        }
    }

    // ------------- customize method ----------------------
    /**
     * search pressed
     */
    private void doSearch() {
        productNo = mSearchEditext.getText().toString();
        if (StringUtil.isEmpty(productNo)) {
            mSearchEditext.startAnimation(mShakeAnimation);
            TipUtil.tipDescription(this, "查询货号不能为空.");
        } else {
            openProgressDialog();
            mGoodsTask = new GoodsTask(this, this, productNo);
            mGoodsTask.execute();
        }
    }

    /**
     * scan pressed
     */
    private void doScan() {
        Intent intent = new Intent();
        intent.setAction("com.whq.knowverywell.david.barcode.SCAN");
        intent.setClass(ProductSearchActivity.this, BarcodeActivity.class);
        startActivityForResult(intent, 0);
    }

}
